import strHtml from "./MyAccountPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { BasePage } from "../BacePage";
import { getCurrentUser, updateUser } from "../../services/userService"; // ✅ 补充 updateUser 引入

export class MyAccountPage extends BasePage {
  constructor() {
    super();
    this.dom = null;
    this.userData = {
      id: null,
      username: "默认用户",
      email: "user@example.com",
      realName: "真实姓名",
      avatar: "./assets/default-avatar.png",
    };
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);

    const saved = localStorage.getItem("account-info");
    if (saved) {
      try {
        this.userData = JSON.parse(saved);
      } catch (e) {
        console.warn("用户数据解析失败，使用默认值");
      }
    }

    await this._loadUserFromServer();
    this._renderUserInfo();
    this._bindEvents();

    return this.dom;
  }

  async _loadUserFromServer() {
    const user = await getCurrentUser();
    if (user) {
      this.userData = {
        id: user.id,
        username: user.username,
        email: user.email,
        realName: user.realName,
        avatar: user.avatar || "./assets/images/users/user-10.jpg",
      };
    }
  }

  _renderUserInfo() {
    const avatarImg = this.dom.querySelector("#profile-avatar");
    const container = this.dom.querySelector("#user-info-container");

    avatarImg.src = this.userData.avatar.startsWith("data:image")
      ? this.userData.avatar
      : `data:image/jpeg;base64,${this.userData.avatar}`;

    container.innerHTML = `
      <div class="row mb-2">
        <label class="col-sm-3 fw-bold">用户名：</label>
        <div class="col-sm-9"><span>${this.userData.username}</span></div>
      </div>
      <div class="row mb-2">
        <label class="col-sm-3 fw-bold">邮箱：</label>
        <div class="col-sm-9"><span>${this.userData.email}</span></div>
      </div>
      <div class="row mb-2">
        <label class="col-sm-3 fw-bold">真实姓名：</label>
        <div class="col-sm-9"><span>${this.userData.realName}</span></div>
      </div>
    `;
  }

  _bindEvents() {
    // ✅ 更换头像并同步后端
    const uploadInput = this.dom.querySelector("#upload-avatar");
    const changeBtn = this.dom.querySelector("#change-avatar-btn");
    const avatarImg = this.dom.querySelector("#profile-avatar");

    changeBtn.addEventListener("click", () => uploadInput.click());
    uploadInput.addEventListener("change", (e) => {
      const file = e.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = async () => {
          const fullBase64 = reader.result;
          const cleaned = fullBase64.replace(/^data:.+;base64,/, ""); // ✅ 清理前缀

          avatarImg.src = fullBase64; // 显示预览图
          this.userData.avatar = cleaned;

          console.log("🔍 发送给后端的 userData:", this.userData);

          try {
            await updateUser(this.userData.id, this.userData); // ✅ 上传到后端
            this._saveToLocal();
            window.dispatchEvent(new Event("user-info-updated"));
          } catch (err) {
            alert("头像更新失败！");
          }
        };
        reader.readAsDataURL(file);
      }
    });

    // 打开编辑弹窗
    const editBtn = this.dom.querySelector("#edit-info-btn");
    editBtn.addEventListener("click", () => {
      this.dom.querySelector("#username-input").value = this.userData.username;
      this.dom.querySelector("#email-input").value = this.userData.email;
      this.dom.querySelector("#realname-input").value = this.userData.realName;
      new bootstrap.Modal(this.dom.querySelector("#editUserModal")).show();
    });

    // ✅ 保存编辑内容并同步后端
    const form = this.dom.querySelector("#edit-user-form");
    form.addEventListener("submit", async (e) => {
      e.preventDefault();
      const updatedUser = {
        username: this.dom.querySelector("#username-input").value,
        email: this.dom.querySelector("#email-input").value,
        realName: this.dom.querySelector("#realname-input").value,
        avatar: this.userData.avatar,
      };

      try {
        await updateUser(this.userData.id, updatedUser); // ✅ 同步到后端
        this.userData = { ...this.userData, ...updatedUser };
        this._saveToLocal();
        this._renderUserInfo();
        bootstrap.Modal.getInstance(
          this.dom.querySelector("#editUserModal")
        ).hide();
      } catch (error) {
        alert("用户信息更新失败！");
      }
    });
  }

  _saveToLocal() {
    localStorage.setItem("account-info", JSON.stringify(this.userData));
  }
}
